<template>
  <view class="withdraw-history">


    <!-- 统计卡片 -->
    <view class="stats-section">
      <view class="stats-card">
        <view class="stat-item">
          <text class="stat-value">{{ stats.total_amount || 0 }}</text>
          <text class="stat-label">累计提现(元)</text>
        </view>
        <view class="stat-divider"></view>
        <view class="stat-item">
          <text class="stat-value">{{ stats.total_count || 0 }}</text>
          <text class="stat-label">提现次数</text>
        </view>
        <view class="stat-divider"></view>
        <view class="stat-item">
          <text class="stat-value">{{ stats.pending_count || 0 }}</text>
          <text class="stat-label">处理中</text>
        </view>
      </view>
    </view>

    <!-- 筛选标签 -->
    <view class="filter-section">
      <scroll-view scroll-x class="filter-scroll">
        <view class="filter-tags">
          <view 
            v-for="status in statusList" 
            :key="status.value"
            class="filter-tag"
            :class="{ active: currentStatus === status.value }"
            @click="changeStatus(status.value)"
          >
            {{ status.label }}
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 提现记录列表 -->
    <view class="records-section">
      <view v-if="loading" class="loading-wrapper">
        <u-loading-icon mode="flower"></u-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>
      
      <view v-else-if="recordList.length === 0" class="empty-wrapper">
        <u-empty text="暂无提现记录" mode="data"></u-empty>
      </view>
      
      <view v-else class="record-list">
        <view 
          v-for="record in recordList" 
          :key="record.id"
          class="record-item"
          @click="goToDetail(record.id)"
        >
          <view class="record-header">
            <view class="record-info">
              <text class="record-amount">¥{{ record.amount }}</text>
              <text class="record-method">{{ getPaymentMethodText(record.payment_method) }}</text>
            </view>
            <view class="record-status">
              <u-tag 
                :text="getStatusText(record.status)" 
                :type="getStatusType(record.status)"
                size="mini"
              ></u-tag>
            </view>
          </view>
          
          <view class="record-details">
            <view class="detail-row">
              <text class="detail-label">申请时间</text>
              <text class="detail-value">{{ formatTime(record.create_time) }}</text>
            </view>
            <view class="detail-row" v-if="record.actual_amount">
              <text class="detail-label">实际到账</text>
              <text class="detail-value">¥{{ record.actual_amount }}</text>
            </view>
            <view class="detail-row" v-if="record.remark">
              <text class="detail-label">备注</text>
              <text class="detail-value">{{ record.remark }}</text>
            </view>
          </view>
          
          <!-- 操作按钮 -->
          <view class="record-actions" v-if="record.status === 'pending'">
            <u-button 
              size="mini" 
              type="error" 
              plain
              @click.stop="cancelWithdraw(record.id)"
            >
              取消申请
            </u-button>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view class="loadmore-section" v-if="recordList.length > 0">
      <u-loadmore 
        :status="loadmoreStatus"
        @loadmore="loadMore"
      ></u-loadmore>
    </view>
  </view>
</template>

<script>
import { getUserWithdraws, getStats, cancel } from '@/api/withdraw'

export default {
  name: 'WithdrawHistory',
  data() {
    return {
      stats: {},
      recordList: [],
      currentStatus: 'all',
      loading: false,
      loadmoreStatus: 'loadmore',
      page: 1,
      pageSize: 10,
      hasMore: true,
      statusList: [
        { value: 'all', label: '全部' },
        { value: 'pending', label: '待审核' },
        { value: 'processing', label: '处理中' },
        { value: 'success', label: '已完成' },
        { value: 'failed', label: '已失败' },
        { value: 'cancelled', label: '已取消' }
      ]
    }
  },
  onLoad() {
    this.loadData()
  },
  onPullDownRefresh() {
    this.refreshData()
  },
  methods: {
    async loadData() {
      await Promise.all([
        this.loadStats(),
        this.loadRecords(true)
      ])
    },
    async refreshData() {
      this.page = 1
      this.hasMore = true
      await this.loadData()
      uni.stopPullDownRefresh()
    },
    async loadStats() {
      try {
        const res = await getStats()
        if (res.code === 0) {
          this.stats = res.data || {}
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
      }
    },
    async loadRecords(reset = false) {
      if (this.loading) return
      
      this.loading = true
      
      try {
        const params = {
          page: reset ? 1 : this.page,
          page_size: this.pageSize
        }
        
        if (this.currentStatus !== 'all') {
          params.status = this.currentStatus
        }
        
        const res = await getUserWithdraws(params)
        
        if (res.code === 0) {
          const newList = res.data.list || []
          
          if (reset) {
            this.recordList = newList
            this.page = 1
          } else {
            this.recordList.push(...newList)
          }
          
          this.hasMore = newList.length >= this.pageSize
          this.page = reset ? 2 : this.page + 1
          
          // 更新加载更多状态
          this.loadmoreStatus = this.hasMore ? 'loadmore' : 'nomore'
        }
      } catch (error) {
        console.error('获取提现记录失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    async loadMore() {
      if (!this.hasMore || this.loading) return
      
      this.loadmoreStatus = 'loading'
      await this.loadRecords()
    },
    changeStatus(status) {
      if (this.currentStatus === status) return
      
      this.currentStatus = status
      this.page = 1
      this.hasMore = true
      this.loadRecords(true)
    },
    async cancelWithdraw(id) {
      const confirmRes = await uni.showModal({
        title: '确认取消',
        content: '确定要取消这笔提现申请吗？',
        confirmText: '确认',
        cancelText: '取消'
      })

      if (!confirmRes.confirm) return

      try {
        const res = await cancel({ id })
        
        if (res.code === 0) {
          uni.showToast({
            title: '取消成功',
            icon: 'success'
          })
          
          // 刷新列表
          this.refreshData()
        } else {
          uni.showToast({
            title: res.msg || '取消失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('取消提现失败:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    },
    goToDetail(id) {
      uni.navigateTo({
        url: `/pages/user/withdraw/detail?id=${id}`
      })
    },
    getPaymentMethodText(method) {
      const methods = {
        wechat: '微信',
        alipay: '支付宝',
        bank: '银行卡'
      }
      return methods[method] || '未知'
    },
    getStatusText(status) {
      const statusMap = {
        pending: '待审核',
        processing: '处理中',
        success: '已完成',
        failed: '已失败',
        cancelled: '已取消'
      }
      return statusMap[status] || '未知'
    },
    getStatusType(status) {
      const typeMap = {
        pending: 'warning',
        processing: 'info',
        success: 'success',
        failed: 'error',
        cancelled: 'info'
      }
      return typeMap[status] || 'info'
    },
    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp * 1000)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },

  }
}
</script>

<style lang="scss" scoped>
.withdraw-history {
  min-height: 100vh;
  background-color: #f8f9fa;
}

.stats-section {
  padding: 20rpx;
  
  .stats-card {
    padding: 40rpx;
    background: white;
    border-radius: 20rpx;
    display: flex;
    align-items: center;
    
    .stat-item {
      flex: 1;
      text-align: center;
      
      .stat-value {
        display: block;
        font-size: 48rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .stat-label {
        display: block;
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .stat-divider {
      width: 1rpx;
      height: 60rpx;
      background: #f0f0f0;
      margin: 0 20rpx;
    }
  }
}

.filter-section {
  padding: 0 20rpx 20rpx;
  
  .filter-scroll {
    white-space: nowrap;
  }
  
  .filter-tags {
    display: flex;
    gap: 20rpx;
    
    .filter-tag {
      padding: 15rpx 30rpx;
      background: white;
      border-radius: 50rpx;
      font-size: 26rpx;
      color: #666;
      white-space: nowrap;
      transition: all 0.3s;
      
      &.active {
        background: #007aff;
        color: white;
      }
    }
  }
}

.records-section {
  margin: 0 20rpx;
}

.loading-wrapper {
  padding: 80rpx 0;
  text-align: center;
  
  .loading-text {
    display: block;
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #999;
  }
}

.empty-wrapper {
  padding: 80rpx 0;
}

.record-list {
  .record-item {
    margin-bottom: 20rpx;
    padding: 30rpx;
    background: white;
    border-radius: 20rpx;
    
    .record-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 20rpx;
      
      .record-info {
        .record-amount {
          display: block;
          font-size: 36rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 5rpx;
        }
        
        .record-method {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
    
    .record-details {
      .detail-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8rpx 0;
        
        .detail-label {
          font-size: 26rpx;
          color: #666;
        }
        
        .detail-value {
          font-size: 26rpx;
          color: #333;
        }
      }
    }
    
    .record-actions {
      margin-top: 20rpx;
      padding-top: 20rpx;
      border-top: 1rpx solid #f0f0f0;
      text-align: right;
    }
  }
}

.loadmore-section {
  padding: 20rpx;
}
</style>
